﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ERP.ERPModels.HumanResources.HumanResourceManagement;
using ERP.EntityFrameworkCore;
using Volo.Abp.Application.Dtos;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace ERP.Web.Controllers.HumanResources.HumanResourceManagement
{
    public class InterviewControlController : Controller
    {
        private readonly ERPDbContext _dbContext;

        public InterviewControlController(ERPDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取面试管理分页列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetInterviewList(string personName, string interviewer, int pageIndex = 1, int pageSize = 10)
        {
            // 1. 获取基础查询
            var query = _dbContext.InterviewControl.AsQueryable();

            // 2. 应用筛选条件
            if (!string.IsNullOrWhiteSpace(personName))
            {
                query = query.Where(x => x.PersonnelName.Contains(personName));
            }

            if (!string.IsNullOrWhiteSpace(interviewer))
            {
                query = query.Where(x => x.Interviewer.Contains(interviewer));
            }

            // 3. 计算总记录数
            var totalCount = await query.CountAsync();

            // 4. 执行分页查询
            var items = await query
                .OrderByDescending(x => x.InterviewsTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            // 5. 构建返回结果
            return Json(new { 
                code = 0, 
                msg = "success", 
                count = totalCount,
                data = items
            });
        }

        

        

        /// <summary>
        /// 发送面试邀请
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> SendInterviewInvitation([FromBody] InterviewInvitationModel model)
        {
            if (model == null)
            {
                return Json(new { code = 500, msg = "参数不能为空" });
            }

            try
            {
                // 创建新的面试记录
                var interviewRecord = new InterviewControl
                {
                    PersonnelCode = model.PersonnelCode,
                    PersonnelName = model.PersonnelName,
                    Phone = model.Phone ?? "",
                    Sex = model.Sex,
                    DefiniteIntegral = model.DefiniteIntegral ?? "",
                    AffiliatedDepartment = model.AffiliatedDepartment,
                    PostWage = model.PostWage,
                    Roles = model.Roles ?? "",
                    Interviewer = model.Interviewer,
                    InterviewFeedback = model.Remarks ?? "未开始面试",
                    InterviewResult = "待面试",
                    InterviewNumber = 1,
                    InterviewsTime = model.InterviewsTime
                };

                await _dbContext.InterviewControl.AddAsync(interviewRecord);
                await _dbContext.SaveChangesAsync();

                // 这里可以添加发送邮件或短信通知的逻辑
                // ...

                return Json(new { code = 0, msg = "面试邀请已发送" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = $"发送面试邀请失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportToExcel(string personnelName = "", string interviewer = "")
        {
            try
            {
                // 1. 获取基础查询
                var query = _dbContext.InterviewControl.AsQueryable();

                // 2. 应用筛选条件
                if (!string.IsNullOrWhiteSpace(personnelName))
                {
                    query = query.Where(x => x.PersonnelName.Contains(personnelName));
                }

                if (!string.IsNullOrWhiteSpace(interviewer))
                {
                    query = query.Where(x => x.Interviewer.Contains(interviewer));
                }

                // 3. 获取数据
                var data = await query
                    .OrderByDescending(x => x.InterviewsTime)
                    .ToListAsync();

                // 4. 导出Excel
                return ExportInterviewsToExcel(data);
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = "导出失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 导出选中的记录到Excel
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ExportSelectedToExcel([FromBody] int[] ids)
        {
            if (ids == null || ids.Length == 0)
            {
                return Json(new { code = 500, msg = "未选择任何记录" });
            }

            try
            {
                // 1. 获取选中的数据
                var data = await _dbContext.InterviewControl
                    .Where(x => ids.Contains(x.Id))
                    .OrderByDescending(x => x.InterviewsTime)
                    .ToListAsync();

                if (data.Count == 0)
                {
                    return Json(new { code = 404, msg = "未找到选中的记录" });
                }

                // 2. 导出Excel
                return ExportInterviewsToExcel(data);
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = "导出失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 将面试记录导出为Excel
        /// </summary>
        private FileResult ExportInterviewsToExcel(List<InterviewControl> data)
        {
            // 1. 创建Excel工作簿
            using var ms = new MemoryStream();
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("面试管理列表");

            // 2. 创建表头
            var headerRow = sheet.CreateRow(0);
            headerRow.CreateCell(0).SetCellValue("人员编码");
            headerRow.CreateCell(1).SetCellValue("人员名称");
            headerRow.CreateCell(2).SetCellValue("联系电话");
            headerRow.CreateCell(3).SetCellValue("性别");
            headerRow.CreateCell(4).SetCellValue("定级");
            headerRow.CreateCell(5).SetCellValue("归属部门");
            headerRow.CreateCell(6).SetCellValue("岗位");
            headerRow.CreateCell(7).SetCellValue("角色");
            headerRow.CreateCell(8).SetCellValue("面试官");
            headerRow.CreateCell(9).SetCellValue("面试反馈");
            headerRow.CreateCell(10).SetCellValue("面试结果");
            headerRow.CreateCell(11).SetCellValue("面试次数");
            headerRow.CreateCell(12).SetCellValue("面试时间");

            // 3. 设置表头样式
            var headerStyle = workbook.CreateCellStyle();
            var headerFont = workbook.CreateFont();
            headerFont.IsBold = true;
            headerStyle.SetFont(headerFont);
            
            for (int i = 0; i < 13; i++)
            {
                headerRow.GetCell(i).CellStyle = headerStyle;
            }

            // 4. 填充数据
            int rowIndex = 1;
            foreach (var item in data)
            {
                var row = sheet.CreateRow(rowIndex++);
                row.CreateCell(0).SetCellValue(item.PersonnelCode);
                row.CreateCell(1).SetCellValue(item.PersonnelName);
                row.CreateCell(2).SetCellValue(item.Phone);
                row.CreateCell(3).SetCellValue(item.Sex == 1 ? "男" : (item.Sex == 2 ? "女" : "未知"));
                row.CreateCell(4).SetCellValue(item.DefiniteIntegral);
                row.CreateCell(5).SetCellValue(item.AffiliatedDepartment);
                row.CreateCell(6).SetCellValue(item.PostWage);
                row.CreateCell(7).SetCellValue(item.Roles);
                row.CreateCell(8).SetCellValue(item.Interviewer);
                row.CreateCell(9).SetCellValue(item.InterviewFeedback);
                row.CreateCell(10).SetCellValue(item.InterviewResult);
                row.CreateCell(11).SetCellValue(item.InterviewNumber.ToString());
                row.CreateCell(12).SetCellValue(item.InterviewsTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            // 5. 自动调整列宽
            for (int i = 0; i < 13; i++)
            {
                sheet.AutoSizeColumn(i);
            }

            // 6. 写入内存流并返回
            workbook.Write(ms);
            
            // 7. 生成文件名
            string fileName = $"面试管理列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            
            // 8. 返回Excel文件
            return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }
    }

    /// <summary>
    /// 面试邀请模型
    /// </summary>
    public class InterviewInvitationModel
    {
        public string PersonnelCode { get; set; }
        public string PersonnelName { get; set; }
        public string Phone { get; set; }
        public int Sex { get; set; }
        public string DefiniteIntegral { get; set; }
        public string AffiliatedDepartment { get; set; }
        public string PostWage { get; set; }
        public string Roles { get; set; }
        public string Interviewer { get; set; }
        public string Remarks { get; set; }
        public DateTime InterviewsTime { get; set; }
    }
}
